package com.andy.module.ext

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import com.andy.module.R
import com.andy.module.uploadphoto.UploadPhotoFragment
import com.andy.ui.view.AndyInputLayout

/**
 * @creator:LuoFan
 * @date:2022/6/13
 * @description:
 */

fun ViewGroup.initUploadFragment(
    fragmentManager: FragmentManager,
    layoutId: Int,
    uploadUrl: String = ""
): UploadPhotoFragment {
    val uploadFragment = UploadPhotoFragment()
    uploadFragment.uploadUrl = uploadUrl
    fragmentManager.beginTransaction().add(layoutId, uploadFragment).commitAllowingStateLoss()
    return uploadFragment
}

fun AndyInputLayout.addTextCheck(textView: TextView) {
    textView.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (visibility == View.VISIBLE) {
                if (s.toString().trim().isNotEmpty()) {
                    hideError()
                } else {
                    setError(R.string.please_enter)
                }
            }
        }
    })
}

fun AndyInputLayout.checkInput(editText: EditText): Boolean {
    if (visibility == View.GONE) {
        return true
    }
    return if (editText.text.toString().trim().isEmpty()) {
        setError(R.string.please_enter)
        false
    } else {
        hideError()
        true
    }
}

fun AndyInputLayout.checkNumberInput(editText: EditText): Boolean {
    if (visibility == View.GONE) {
        return true
    }
    return if (editText.text.toString().trim().isEmpty()) {
        setError(R.string.please_enter)
        false
    } else {
        hideError()
        true
    }
}

fun AndyInputLayout.checkPhoneInput(editText: EditText): Boolean {
    if (visibility == View.GONE) {
        return true
    }
    return if (editText.text.toString().trim().isEmpty()) {
        setError(R.string.please_enter)
        false
    } else {
        return if (editText.text.toString().length == 11) {
            hideError()
            true
        } else {
            setError(R.string.please_enter_phone_number)
            false
        }
    }
}

fun AndyInputLayout.checkChoose(textView: TextView): Boolean {
    if (visibility == View.GONE) {
        return true
    }
    return if (textView.text.toString().trim().isEmpty()) {
        setError(R.string.please_select)
        false
    } else {
        hideError()
        true
    }
}